package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 在进入主页面之前先检查用户是否进行登录,如果没有,则先进行登录
 */
@Slf4j
@WebFilter("/*")
public class loginFilter implements Filter {
    //专门用来匹配路径的,且支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();

        log.info("拦截到的路径为" + uri);
        //1.设置拦截路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2.判断本次请求是否需要处理
        boolean check = check(urls, uri);
        //3.如果不需要进行处理,则直接放行即可
        if(check){
            log.info("本次请求不需要处理" + uri);
            chain.doFilter(request,response);
            return ;
        }
        //4-1.判断登录状态,如果已经登录,则直接放行(电脑端)
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已成功登陆,用户的id为" + request.getSession().getAttribute("employee"));
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            chain.doFilter(request,response);
            return ;
        }
        //4-2.判断登录状态,如果已经登录,则直接放行(移动端)
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已成功登陆,用户的id为:{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            long id = Thread.currentThread().getId();
            log.info("线程id:{}",id);
            chain.doFilter(request,response);
            return ;
        }
        log.info("用户未登录");
        //5.如果未登录则返回未登录结果,通过输出流返回给客户端
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配,按断本次请求是否需要放行
     * @param urls
     * @param uri
     * @return
     */
    public boolean check(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if(match){
                return true;
            }
        }
        return false;
    }

}
